import React, { useState, useEffect, useCallback, useRef } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from './ui/card';
import { Button } from './ui/button';
import { Progress } from './ui/progress';
import { Badge } from './ui/badge';
import { Target, Timer, Zap, RotateCcw, MousePointer, Trophy } from 'lucide-react';

interface TestResult {
  testType: string;
  score: number;
  details: string;
  timestamp: Date;
}

interface CoordinationTestProps {
  onComplete: (result: TestResult) => void;
}

type TestState = 'ready' | 'testing' | 'complete';

interface TargetCircle {
  id: number;
  x: number;
  y: number;
  size: number;
  timeToLive: number;
  hit: boolean;
  createdAt: number;
}

interface HitResult {
  accuracy: number;
  time: number;
  size: number;
}

export function CoordinationTest({ onComplete }: CoordinationTestProps) {
  const [state, setState] = useState<TestState>('ready');
  const [targets, setTargets] = useState<TargetCircle[]>([]);
  const [hits, setHits] = useState<HitResult[]>([]);
  const [misses, setMisses] = useState(0);
  const [timeLeft, setTimeLeft] = useState(30);
  const [mousePosition, setMousePosition] = useState({ x: 0, y: 0 });
  
  const containerRef = useRef<HTMLDivElement>(null);
  const gameIntervalRef = useRef<NodeJS.Timeout | null>(null);
  const timerIntervalRef = useRef<NodeJS.Timeout | null>(null);
  const targetTimeoutsRef = useRef<Map<number, NodeJS.Timeout>>(new Map());
  
  const testDuration = 30;
  const targetInterval = 1200;
  const targetLifetime = 2000;
  const minTargetSize = 30;
  const maxTargetSize = 80;

  // Clear all timeouts and intervals
  const clearAllTimers = useCallback(() => {
    if (gameIntervalRef.current) {
      clearInterval(gameIntervalRef.current);
      gameIntervalRef.current = null;
    }
    if (timerIntervalRef.current) {
      clearInterval(timerIntervalRef.current);
      timerIntervalRef.current = null;
    }
    targetTimeoutsRef.current.forEach(timeout => clearTimeout(timeout));
    targetTimeoutsRef.current.clear();
  }, []);

  // Generate a new target
  const generateTarget = useCallback(() => {
    if (!containerRef.current) return;
    
    const rect = containerRef.current.getBoundingClientRect();
    const size = minTargetSize + Math.random() * (maxTargetSize - minTargetSize);
    const margin = size / 2 + 10;
    
    const target: TargetCircle = {
      id: Date.now() + Math.random(),
      x: margin + Math.random() * (rect.width - 2 * margin),
      y: margin + Math.random() * (rect.height - 2 * margin),
      size,
      timeToLive: targetLifetime,
      hit: false,
      createdAt: Date.now()
    };
    
    setTargets(prev => [...prev, target]);
    
    // Set timeout to remove target
    const timeoutId = setTimeout(() => {
      setTargets(prev => {
        const targetToRemove = prev.find(t => t.id === target.id);
        // Only count miss if we're still testing
        if (targetToRemove && !targetToRemove.hit) {
          setMisses(prevMisses => prevMisses + 1);
        }
        return prev.filter(t => t.id !== target.id);
      });
      targetTimeoutsRef.current.delete(target.id);
    }, targetLifetime);
    
    targetTimeoutsRef.current.set(target.id, timeoutId);
  }, [targetLifetime, minTargetSize, maxTargetSize]);

  // Start the test
  const startTest = useCallback(() => {
    console.log('Starting test...');
    setState('testing');
    setTimeLeft(testDuration);
    setTargets([]);
    setHits([]);
    setMisses(0);
    
    // Start timer
    console.log('Setting up timer...');
    const timer = setInterval(() => {
      setTimeLeft(prev => {
        console.log('Timer tick:', prev - 1);
        if (prev <= 1) {
          clearInterval(timer);
          setState('complete');
          return 0;
        }
        return prev - 1;
      });
    }, 1000);
    timerIntervalRef.current = timer;

    // Start generating targets
    console.log('Setting up target generation...');
    const gameTimer = setInterval(() => {
      console.log('Generating target...');
      generateTarget();
    }, targetInterval);
    gameIntervalRef.current = gameTimer;
    
    // Generate first target immediately
    setTimeout(() => {
      console.log('Generating first target...');
      generateTarget();
    }, 500);
  }, [testDuration, targetInterval, generateTarget]);

  // Handle target click
  const handleTargetClick = useCallback((target: TargetCircle, event: React.MouseEvent) => {
    if (target.hit) return;
    
    event.stopPropagation();
    console.log('Target clicked:', target.id);
    
    const rect = event.currentTarget.getBoundingClientRect();
    const centerX = rect.left + rect.width / 2;
    const centerY = rect.top + rect.height / 2;
    const clickX = event.clientX;
    const clickY = event.clientY;
    
    const distance = Math.sqrt(
      Math.pow(clickX - centerX, 2) + Math.pow(clickY - centerY, 2)
    );
    
    const accuracy = Math.max(0, 1 - (distance / (target.size / 2)));
    const reactionTime = Date.now() - target.createdAt;
    
    const hitResult: HitResult = {
      accuracy,
      time: reactionTime,
      size: target.size
    };
    
    setHits(prev => [...prev, hitResult]);
    setTargets(prev => prev.map(t => 
      t.id === target.id ? { ...t, hit: true } : t
    ));
    
    // Remove hit target after short delay
    setTimeout(() => {
      setTargets(prev => prev.filter(t => t.id !== target.id));
    }, 200);
    
    // Clear the timeout for this target
    const timeout = targetTimeoutsRef.current.get(target.id);
    if (timeout) {
      clearTimeout(timeout);
      targetTimeoutsRef.current.delete(target.id);
    }
  }, []);

  // Handle mouse movement
  const handleMouseMove = useCallback((event: React.MouseEvent) => {
    if (!containerRef.current) return;
    
    const rect = containerRef.current.getBoundingClientRect();
    setMousePosition({
      x: event.clientX - rect.left,
      y: event.clientY - rect.top
    });
  }, []);

  // Reset test
  const resetTest = useCallback(() => {
    clearAllTimers();
    setState('ready');
    setTimeLeft(testDuration);
    setTargets([]);
    setHits([]);
    setMisses(0);
  }, [clearAllTimers, testDuration]);

  // Update target timeToLive
  useEffect(() => {
    if (state !== 'testing') return;
    
    const updateInterval = setInterval(() => {
      setTargets(prev => prev.map(target => ({
        ...target,
        timeToLive: Math.max(0, target.timeToLive - 50)
      })));
    }, 50);

    return () => clearInterval(updateInterval);
  }, [state]);

  // Cleanup on test completion
  useEffect(() => {
    if (state === 'complete') {
      clearAllTimers();
    }
  }, [state, clearAllTimers]);

  // Cleanup on unmount
  useEffect(() => {
    return () => {
      clearAllTimers();
    };
  }, [clearAllTimers]);

  // Statistics
  const getStats = () => {
    const totalTargets = hits.length + misses;
    const hitRate = totalTargets > 0 ? (hits.length / totalTargets) * 100 : 0;
    const avgAccuracy = hits.length > 0 ? hits.reduce((sum, hit) => sum + hit.accuracy, 0) / hits.length : 0;
    const avgReactionTime = hits.length > 0 ? hits.reduce((sum, hit) => sum + hit.time, 0) / hits.length : 0;
    
    return {
      totalTargets,
      hits: hits.length,
      misses,
      hitRate,
      avgAccuracy: avgAccuracy * 100,
      avgReactionTime
    };
  };

  const getFinalScore = () => {
    const stats = getStats();
    let score = stats.hitRate;
    score += stats.avgAccuracy * 0.3;
    const speedBonus = Math.max(0, (2000 - stats.avgReactionTime) / 2000) * 20;
    score += speedBonus;
    const volumeBonus = Math.min(stats.hits / 15, 1) * 10;
    score += volumeBonus;
    return Math.min(100, Math.max(0, Math.round(score)));
  };

  const getRating = () => {
    const score = getFinalScore();
    if (score >= 90) return { text: '神枪手', color: 'text-yellow-500' };
    if (score >= 80) return { text: '优秀', color: 'text-green-500' };
    if (score >= 70) return { text: '良好', color: 'text-blue-500' };
    if (score >= 60) return { text: '一般', color: 'text-gray-500' };
    return { text: '需要练习', color: 'text-orange-500' };
  };

  const handleComplete = () => {
    const stats = getStats();
    const result: TestResult = {
      testType: '手眼协调测试',
      score: getFinalScore(),
      details: `命中率 ${Math.round(stats.hitRate)}%, 平均准确率 ${Math.round(stats.avgAccuracy)}%, 平均反应时间 ${Math.round(stats.avgReactionTime)}ms`,
      timestamp: new Date()
    };
    onComplete(result);
  };

  if (state === 'complete') {
    const stats = getStats();
    const rating = getRating();
    
    return (
      <div className="max-w-2xl mx-auto space-y-6">
        <Card>
          <CardHeader className="text-center">
            <CardTitle className="flex items-center justify-center gap-2">
              <Trophy className="w-6 h-6 text-red-500" />
              测试完成！
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="text-center space-y-4">
              <div className="text-6xl font-bold text-primary">
                {getFinalScore()}
              </div>
              <div className={`text-xl font-semibold ${rating.color}`}>
                {rating.text}
              </div>
            </div>

            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              <div className="text-center p-4 bg-green-50 dark:bg-green-950 rounded-lg">
                <div className="text-2xl font-bold text-green-600">{stats.hits}</div>
                <div className="text-sm text-muted-foreground">命中目标</div>
              </div>
              <div className="text-center p-4 bg-red-50 dark:bg-red-950 rounded-lg">
                <div className="text-2xl font-bold text-red-600">{stats.misses}</div>
                <div className="text-sm text-muted-foreground">错过目标</div>
              </div>
              <div className="text-center p-4 bg-blue-50 dark:bg-blue-950 rounded-lg">
                <div className="text-2xl font-bold text-blue-600">{Math.round(stats.hitRate)}%</div>
                <div className="text-sm text-muted-foreground">命中率</div>
              </div>
              <div className="text-center p-4 bg-purple-50 dark:bg-purple-950 rounded-lg">
                <div className="text-2xl font-bold text-purple-600">{Math.round(stats.avgAccuracy)}%</div>
                <div className="text-sm text-muted-foreground">平均精度</div>
              </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="text-center p-4 bg-muted rounded-lg">
                <div className="text-xl font-bold">{Math.round(stats.avgReactionTime)}ms</div>
                <div className="text-sm text-muted-foreground">平均反应时间</div>
              </div>
              <div className="text-center p-4 bg-muted rounded-lg">
                <div className="text-xl font-bold">{stats.totalTargets}</div>
                <div className="text-sm text-muted-foreground">总目标数</div>
              </div>
            </div>

            <div className="flex gap-4">
              <Button onClick={resetTest} variant="outline" className="flex-1">
                <RotateCcw className="w-4 h-4 mr-2" />
                重新测试
              </Button>
              <Button onClick={handleComplete} className="flex-1">
                保存结果
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="max-w-2xl mx-auto space-y-6">
      {state === 'testing' && (
        <Card>
          <CardContent className="pt-6">
            <div className="flex justify-between items-center mb-4">
              <div className="flex items-center gap-4">
                <div className="flex items-center gap-2">
                  <Timer className="w-4 h-4" />
                  <span className="font-mono text-lg">{timeLeft}s</span>
                </div>
                <Badge variant={timeLeft > 20 ? 'secondary' : timeLeft > 10 ? 'default' : 'destructive'}>
                  {timeLeft > 20 ? '充足时间' : timeLeft > 10 ? '注意时间' : '时间紧急'}
                </Badge>
              </div>
              <div className="flex items-center gap-4">
                <div className="text-sm text-green-600">
                  <Target className="w-4 h-4 inline mr-1" />
                  {hits.length}
                </div>
                <div className="text-sm text-red-600">
                  <Zap className="w-4 h-4 inline mr-1" />
                  {misses}
                </div>
                <div className="text-sm text-blue-600">
                  <MousePointer className="w-4 h-4 inline mr-1" />
                  {Math.round((hits.length / Math.max(hits.length + misses, 1)) * 100)}%
                </div>
              </div>
            </div>
            <Progress value={((testDuration - timeLeft) / testDuration) * 100} />
          </CardContent>
        </Card>
      )}

      <Card>
        {state === 'ready' && (
          <>
            <CardHeader className="text-center">
              <CardTitle className="flex items-center justify-center gap-2">
                <Target className="w-6 h-6 text-red-500" />
                手眼协调测试
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-6">
              <div className="text-center space-y-4">
                <p className="text-muted-foreground">
                  在 {testDuration} 秒内，快速准确地点击出现的圆形目标。
                </p>
                <div className="flex justify-center gap-4">
                  <Badge variant="outline">
                    <Timer className="w-3 h-3 mr-1" />
                    {testDuration} 秒
                  </Badge>
                  <Badge variant="outline">
                    <Target className="w-3 h-3 mr-1" />
                    动态目标
                  </Badge>
                  <Badge variant="outline">
                    <Zap className="w-3 h-3 mr-1" />
                    速度精度并重
                  </Badge>
                </div>
              </div>
              <div className="text-center">
                <Button 
                  size="lg" 
                  onClick={startTest}
                  className="bg-gradient-to-r from-slate-400 to-gray-500 hover:from-slate-500 hover:to-gray-600 text-white shadow-lg hover:shadow-xl transform hover:scale-105 transition-all duration-300 border-0 min-w-[140px] h-12"
                >
                  <Target className="w-5 h-5 mr-2" />
                  开始测试
                </Button>
              </div>
            </CardContent>
          </>
        )}

        {state === 'testing' && (
          <CardContent className="p-0">
            <div 
              ref={containerRef}
              className="relative w-full h-96 bg-gradient-to-br from-blue-50 to-purple-50 dark:from-blue-950 dark:to-purple-950 overflow-hidden cursor-crosshair"
              onMouseMove={handleMouseMove}
            >
              {/* Mouse cursor indicator */}
              <div 
                className="absolute w-3 h-3 bg-red-500 rounded-full pointer-events-none z-20 ring-2 ring-white shadow-lg transition-all duration-75"
                style={{
                  left: mousePosition.x - 6,
                  top: mousePosition.y - 6
                }}
              />
              
              {/* Targets */}
              {targets.map(target => {
                const opacity = Math.max(0.3, target.timeToLive / targetLifetime);
                
                return (
                  <div
                    key={target.id}
                    className={`absolute rounded-full cursor-pointer transition-all duration-200 z-10 ${
                      target.hit 
                        ? 'bg-green-500 scale-150' 
                        : 'bg-red-500 hover:bg-red-600 hover:scale-110 active:scale-95'
                    }`}
                    style={{
                      left: target.x - target.size / 2,
                      top: target.y - target.size / 2,
                      width: target.size,
                      height: target.size,
                      opacity: target.hit ? 0 : opacity,
                      border: '4px solid white',
                      boxShadow: target.hit 
                        ? '0 4px 20px rgba(34, 197, 94, 0.6)' 
                        : '0 4px 15px rgba(239, 68, 68, 0.4), 0 2px 8px rgba(0,0,0,0.2)',
                      filter: target.hit ? 'brightness(1.2)' : 'none'
                    }}
                    onClick={(e) => handleTargetClick(target, e)}
                  >
                    {/* Center dot */}
                    <div 
                      className="absolute bg-white rounded-full shadow-inner"
                      style={{
                        width: target.size * 0.25,
                        height: target.size * 0.25,
                        left: '50%',
                        top: '50%',
                        transform: 'translate(-50%, -50%)'
                      }}
                    />
                    
                    {/* Target rings for better visibility */}
                    <div 
                      className="absolute border-2 border-white/50 rounded-full"
                      style={{
                        width: target.size * 0.6,
                        height: target.size * 0.6,
                        left: '50%',
                        top: '50%',
                        transform: 'translate(-50%, -50%)'
                      }}
                    />
                  </div>
                );
              })}

              {/* Instructions overlay */}
              <div className="absolute top-4 left-4 right-4 text-center z-30">
                <p className="text-sm text-muted-foreground bg-background/90 px-3 py-1 rounded border shadow-sm">
                  点击红色圆形目标的中心
                </p>
              </div>
            </div>

            {/* Real-time stats */}
            <div className="p-4">
              <div className="grid grid-cols-4 gap-4">
                <div className="text-center p-3 bg-green-50 dark:bg-green-950 rounded-lg">
                  <div className="text-lg font-bold text-green-600">{hits.length}</div>
                  <div className="text-xs text-muted-foreground">命中</div>
                </div>
                <div className="text-center p-3 bg-red-50 dark:bg-red-950 rounded-lg">
                  <div className="text-lg font-bold text-red-600">{misses}</div>
                  <div className="text-xs text-muted-foreground">错过</div>
                </div>
                <div className="text-center p-3 bg-blue-50 dark:bg-blue-950 rounded-lg">
                  <div className="text-lg font-bold text-blue-600">
                    {Math.round((hits.length / Math.max(hits.length + misses, 1)) * 100)}%
                  </div>
                  <div className="text-xs text-muted-foreground">命中率</div>
                </div>
                <div className="text-center p-3 bg-purple-50 dark:bg-purple-950 rounded-lg">
                  <div className="text-lg font-bold text-purple-600">
                    {hits.length > 0 ? Math.round((hits.reduce((sum, hit) => sum + hit.accuracy, 0) / hits.length) * 100) : 0}%
                  </div>
                  <div className="text-xs text-muted-foreground">精度</div>
                </div>
              </div>
            </div>
          </CardContent>
        )}
      </Card>

      <Card>
        <CardContent className="pt-6">
          <h3 className="font-semibold mb-2">测试说明</h3>
          <ul className="text-sm text-muted-foreground space-y-1">
            <li>• 测试时长为 {testDuration} 秒</li>
            <li>• 快速准确地点击红色圆形目标</li>
            <li>• 目标会在2秒后自动消失</li>
            <li>• 点击越接近中心，精度越高</li>
            <li>• 反应速度和精度都会影响得分</li>
          </ul>
        </CardContent>
      </Card>
    </div>
  );
}